<template>
  <ZZDialog class="settings" title="我的标记" @close="callbackClose()">
    <el-upload v-model:file-list="fileList" class="upload-demo" accept="" :on-change="handleChange" v-show="false">
      <template #trigger>
        <el-button type="primary" ref="updata">select file</el-button>
      </template>
    </el-upload>
    <div class="mp_head">
      <ul>
        <li @click="drawPoint()"><i class="fa fa-edit" title="添加注记"></i></li>
        <li class="ml10">|</li>
        <li @click="openfile1()"><i class="fa fa-folder-open-o" title="打开文件"></i></li>
        <li @click="openfile2()"><i class="fa fa-folder-open" title="叠加文件"></i></li>
        <li @click="savefile()"><i class="fa fa-save" title="保存文件"></i></li>
        <li class="ml10">|</li>
        <li @click="deleteAll()"><i class="fa fa-trash" title="清空标记"></i></li>
        <li @click="isplotedit()"><i :class="classeidt" title="是否可编辑"></i></li>
      </ul>
    </div>

    <el-table
      :data="tableData"
      row-key="name"
      style="width: 100%,min-height:200px;max-height:600px;"
      highlight-current-row
      @row-dblclick="handleCurrentChange"
    >
      <el-table-column prop="id" label="id" v-if="false" />
      <el-table-column fixed prop="name" label="名称" sortable column-key="name" />
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleClick(scope.row.id)">
            <i class="fa fa-trash" title="删除"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </ZZDialog>
</template>

<script setup lang="ts">
import { LocalStorageUser } from '@/utils/localStorage';
import { DateFormat } from '@/utils/dateFormat';
import { ref, onBeforeMount, onMounted, getCurrentInstance } from 'vue';
import { useViewer } from '@/stores/viewer';
import ZZDialog from '@/common/ZZDialog.vue';
import type { UploadProps, UploadUserFile } from 'element-plus';
import markerpng from '@/components/tools/addmarker/img/marker.png';
const proxy: any = getCurrentInstance()?.proxy;
let viewer: any; //场景视图
let drawControl: any = null;
let editable: boolean = true;
const classeidt = ref('fa fa-unlock');
let isClearForOpenFile: boolean = false;
const label_font_style: string = 'normal small-caps normal 19px 楷体';
const storageName: string = 'wisemapgis_addmarker';

const clearPlotFile = function () {
  fileList.value.slice(0);
};

const fileList = ref<UploadUserFile[]>([]);

const handleChange: UploadProps['onChange'] = (uploadFile: any, _uploadFiles) => {
  fileList.value = fileList.value.slice(-3);
  const fileName = uploadFile.name;
  const fileType = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length).toLowerCase();
  if (fileType != 'json') {
    clearPlotFile();
    return;
  }

  const reader = new FileReader();
  reader.readAsText(uploadFile.raw, 'UTF-8');
  reader.onloadend = function (e: any) {
    const strjson = JSON.parse(e.target?.result);
    jsonToLayer(strjson, isClearForOpenFile);
    clearPlotFile();
  };
};
const hasEdit = function (val: boolean) {
  editable = val;
  drawControl.hasEdit(val);
};

const openfile1 = function () {
  isClearForOpenFile = true;
  proxy.$refs.updata.$el.click();
};
const openfile2 = function () {
  isClearForOpenFile = false;
  proxy.$refs.updata.$el.click();
};
const savefile = function () {
  const data = getJsonData();
  const blob = new Blob([data]);
  const aLink = document.createElement('a');
  aLink.download = 'fileName.json';
  aLink.href = URL.createObjectURL(blob);
  document.body.appendChild(aLink);
  aLink.click();
  document.body.removeChild(aLink);
};
const isplotedit = function () {
  editable = !editable;

  if (editable) {
    classeidt.value = 'fa fa-unlock';
  } else {
    classeidt.value = 'fa fa-lock';
  }
  hasEdit(editable);
};
const drawPoint = function () {
  drawControl.stopDraw();
  drawControl.startDraw({
    type: 'billboard',
    style: {
      scale: 1,
      image: markerpng
    }
  });
};

const bindMarkerEx = function (entity: any) {
  if (entity == null || entity.position == null) return;
  entity.attribute.attr = entity.attribute.attr || {};
  entity.attribute.attr.id = 0; //(new Date()).format("yyyyMMddHHmmss");
  entity.attribute.attr.name = '我的标记';
  entity.label = getLabelStyle(entity.attribute.attr.name);
  entity.billboard.scaleByDistance = new Cesium.NearFarScalar(1.5e2, 1, 8.0e6, 0.2);

  saveEntity(entity, function () {
    entity.popup = {
      html: function (entity: any) {
        return getMarkerInhtml(entity.attribute.attr);
      },
      anchor: [0, -35],
      clickcallback: function () {
        const addmaker = document.getElementById('addmarker_save') as HTMLDivElement | null;
        addmaker?.addEventListener('click', saveEditFeature);

        const delmaker = document.getElementById('addmarker_del') as HTMLDivElement | null;
        delmaker?.addEventListener('click', deleteEditFeature);
      }
    };

    viewer.zz.popup.show(entity, entity.position._value);
  });
};
//========================
const saveEditFeature = function (_event: any) {
  const id = Number((document.getElementById('addmarker_attr_id') as HTMLInputElement)?.value);
  const name = (document.getElementById('addmarker_attr_name') as HTMLInputElement)?.value;
  const remark = (document.getElementById('addmarker_attr_remark') as HTMLInputElement)?.value;
  const entity = drawControl.getEntityById(id);

  entity.attribute.attr = entity.attribute.attr || {};
  entity.attribute.attr.name = name; //$.trim($("#addmarker_attr_name").val());
  entity.attribute.attr.remark = remark; // proxy.$refs.remark.$el.value//$.trim($("#addmarker_attr_remark").val());

  viewer.zz.popup.close();
  entity.label.text = entity.attribute.attr.name;

  saveEntity(entity, '');
  getMarkerDataList();
};

const deleteEditFeaturebyid = function (id: string) {
  const entity = drawControl.getEntityById(id);
  drawControl.deleteEntity(entity);

  viewer.zz.popup.close();

  {
    //浏览器本地存储
    const storagedata = getJsonData();
    LocalStorageUser.add(storageName, storagedata);
  }
  getMarkerDataList();
};

const deleteEditFeature = function (_event: any) {
  const id = (document.getElementById('addmarker_attr_id') as HTMLInputElement)?.value;
  const entity = drawControl.getEntityById(id);
  drawControl.deleteEntity(entity);

  viewer.zz.popup.close();

  {
    //浏览器本地存储
    const storagedata = getJsonData();
    LocalStorageUser.add(storageName, storagedata);
  }
  getMarkerDataList();
};

const getMarkerInhtml = function (attr: any) {
  let inhtml;
  if (editable) {
    if (!attr.name || attr.name == '我的标记') attr.name = '';
    if (!attr.remark) attr.remark = '';
    if (!attr.id) attr.id = '0';
    inhtml =
      '<div class="addmarker-popup-titile">添加标记</div><div class="addmarker-popup-content" ><form >' +
      ' <input type="text" id="addmarker_attr_id" class="form-control" style="display:none" value="' +
      attr.id +
      '"  /> </div>' +
      '<div class="form-group"  style="margin:10px;">  <label for="addmarker_attr_name">名称:&nbsp;&nbsp; </label><input type="text" id="addmarker_attr_name" class="form-control" value="' +
      attr.name +
      '" placeholder="请输入标记名称"    /> </div>' +
      '<div class="form-group" style="margin:10px;">  <label for="addmarker_attr_remark">备注:&nbsp;&nbsp; </label><textarea id="addmarker_attr_remark" class="form-control" rows="3" style="resize: none;" placeholder="请输入备注（可选填）"   >' +
      attr.remark +
      '</textarea></div>' +
      '<div class="form-group" style="text-align: center; "><input style="cursor: pointer;" type="button" class="btn btn-primary  btn-sm" value="保存" id="addmarker_save">&nbsp;&nbsp;<input type="button" style="cursor: pointer;"  class="btn btn-danger  btn-sm" value="删除" id="addmarker_del" /></div>' +
      '</form></div>';
  } else {
    inhtml =
      '<div class="addmarker-popup-titile">我的标记</div><div class="addmarker-popup-content" ><form >' +
      '<div class="form-group"><label>名称</label>：' +
      attr.name +
      '</div>' +
      '<div class="form-group"><label>备注</label>：' +
      attr.remark +
      '</div>' +
      '</form></div>';
  }
  return inhtml;
};
const centerAt = function (id: string) {
  const entity = drawControl.getEntityById(id);
  if (entity) {
    //参数解释：点数据：radius控制视距距离
    viewer.zz.flyTo(entity, { radius: 2500 });
  }
};
const deleteAll = function () {
  drawControl.deleteAll();
  {
    //浏览器本地存储
    //本地存储
    LocalStorageUser.del(storageName);
  }
  getMarkerDataList();
};

const getLabelStyle = function (name: any) {
  return new Cesium.LabelGraphics({
    text: name == '' ? '我的标记' : name,
    font: label_font_style,
    style: Cesium.LabelStyle.FILL_AND_OUTLINE,
    outlineColor: Cesium.Color.BLACK,
    outlineWidth: 3,
    horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
    verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
    pixelOffset: new Cesium.Cartesian2(0, -50),
    distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 200000)
  });
};
const getJsonData = function () {
  const arr = [];
  const arrEntity = drawControl.getEntitys();
  for (let i = 0, len = arrEntity.length; i < len; i++) {
    const entity = arrEntity[i];
    const attr = entity.attribute.attr;
    const coord = zz3d.draw.attr.billboard.getCoordinates(entity);

    const item = {
      id: attr.id,
      name: attr.name,
      remark: attr.remark,
      x: coord[0][0],
      y: coord[0][1],
      z: coord[0][2]
    };
    arr.push(item);
  }
  return JSON.stringify(arr);
};
const jsonToLayer = function (arr: any, isclear: any) {
  if (arr == null || arr.length == 0) return;
  if (isclear) {
    drawControl.deleteAll();
  }
  const arrEntity = [];
  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];
    if (!item.x || !item.y) continue;

    const attribute = {
      type: 'billboard',
      attr: {
        id: item.id || '',
        name: item.name || '',
        remark: item.remark || ''
      },
      style: {
        scale: 1,
        image: markerpng
      }
    };

    if (!isclear) {
      //叠加时，清除已有同id数据
      const entity = drawControl.getEntityById(attribute.attr.id);
      drawControl.deleteEntity(entity);
    }

    const position = Cesium.Cartesian3.fromDegrees(item.x, item.y, item.z || 0.0);
    const entity = drawControl.attributeToEntity(attribute, position);
    entity.popup = {
      html: function (entity: any) {
        return getMarkerInhtml(entity.attribute.attr);
      },
      anchor: [0, -35]
    };
    entity.billboard.scaleByDistance = new Cesium.NearFarScalar(1.5e2, 1, 8.0e6, 0.2);
    entity.label = getLabelStyle(attribute.attr.name);
    arrEntity.push(entity);
  }
  getMarkerDataList();
  viewer.flyTo(arrEntity, { duration: 2.0 });
};

const getMarkerDataList = function () {
  tableData.value.length = 0;
  const arrEntity = drawControl.getEntitys();
  for (let i = 0, len = arrEntity.length; i < len; i++) {
    if (!arrEntity[i].attribute.attr.name) arrEntity[i].attribute.attr.name = '我的标记';
    tableData.value.push(arrEntity[i].attribute.attr);
  }
};

const getList = function () {
  {
    //读取本地存储
    const laststorage = LocalStorageUser.get(storageName); //读取localStorage值
    if (laststorage != null && laststorage != 'null') {
      const arr = JSON.parse(laststorage);

      jsonToLayer(arr, true);
    }
  }
  getMarkerDataList();
};
const saveEntity = function (entity: any, endfun: any) {
  {
    //浏览器本地存储
    if (entity.attribute.attr.id == '0') entity.attribute.attr.id = DateFormat(new Date().toString(), 'yyyyMMddhhmmss');

    const storagedata = getJsonData();
    LocalStorageUser.add(storageName, storagedata);

    if (endfun) endfun();
  }
};

onBeforeMount(() => {
  viewer = useViewer().viewer;
});
onMounted(() => {
  drawControl = new zz3d.Draw(viewer, {
    hasEdit: false
  });

  //事件监听

  drawControl.on(zz3d.draw.event.DrawCreated, function (e: any) {
    const entity = e.entity;
    bindMarkerEx(entity);
  });
  drawControl.on(zz3d.draw.event.EditMovePoint, function (e: any) {
    //编辑修改了点
    const entity = e.entity;

    saveEntity(entity, '');
  });

  getList();
});
const callbackClose = function () {
  drawControl.deleteAll();
};

const handleCurrentChange = function (val: any | undefined) {
  console.log(val.name);
  centerAt(val.id);
};

// function findname(val: any) {
//   return val.name;
// }
const handleClick = (id: string) => {
  deleteEditFeaturebyid(id);
};

const tableData = ref([{ id: '0', name: '', remark: '' }]);
</script>
<style scoped lang="less">
.settings {
  position: absolute;
  top: 100px;
  width: 280px;
  right: 200px;
}

.mp_head {
  line-height: 35px;
  border-bottom: #dedede 1px solid;
  overflow: hidden;

  ul {
    padding: 0;

    li {
      padding: 0;
      float: left;
      display: inline-block;

      i {
        width: 28px;
        height: 25px;
        line-height: 25px;
        text-align: center;
        background: #f5f5f5;
        border: #dedede 1px solid;
        color: #3374e0;
        display: inline-block;
        font-size: 16px;
        margin-left: 10px;
        cursor: pointer;
      }
    }
  }
}

.ml10 {
  margin-left: 10px;
}

.mp_head2 {
  width: 100%;
  height: 45px;
  line-height: 45px;
  text-align: center;
}

.dark .mp_head ul li i {
  background-color: rgba(63, 72, 84, 0.6);
  border: #dedede 1px solid;
  color: #ffffff;
}

/* 2017-11-14 13:31:05 | 修改 木遥（微信:  http://marsgis.cn/weixin.html ） */
.addmarker-popup-titile {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  border-radius: 3px 3px 0 0;
  padding: 0 80px 0 20px;
  height: 42px;
  line-height: 42px;
  font-size: 16px;
  color: white;
  background-color: #20a0ff;
  border-bottom: 1px solid #eee;
  overflow: hidden;
}

.addmarker-popup-content {
  width: 260px;
  margin-top: 52px;
  font-size: 14px;
}
</style>
